import {useMemberStore} from '@/stores'
const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
//添加拦截器
const httpInterceptor = {
  //1拦截前触发
  invoke(options:UniApp.RequestOptions) {
    if (!options.url.startsWith('http')) {
      options.url=baseURL+options.url
    }
    //请求超时，默认60s
    options.timeout = 10000;
    //3.添加请求头标识
    options.header = {
      //保存原有树形
      ...options.header,
      //'source-client': 'miniapp' 是一个新的键值对，表示在请求头中添加一个名为 source-client 的属性，其值为 'miniapp'。
      'source-client':'miniapp',
    }
    //4.添加token请求头标识
    const MemberStore = useMemberStore()
    const token = MemberStore.profile?.token
    if (token) {
      options.header.Authorization=token
    }
  }
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)
//指定数据类型
interface Data<T>{
  code: string,
  msg: string,
  result:T,
}
//添加类型接收泛型
export const http =<T> (options: UniApp.RequestOptions) => {
  //1.返回promise对象
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      //2.请求成功
      success(res) {
        //提取核心数据
        resolve(res.data as Data<T>)
      }
    })
  })
}